<template>
  <div class="news-list">

    <div style="display:flex;justify-content: space-between;margin:0 0 10px;">
        <div style="display:flex;align-items: center;">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="标题">
              <el-input clearable size="small" v-model="formInline.title" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item label="分类">
              <el-select clearable size="small" v-model="formInline.classify" placeholder="请选择">
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select clearable size="small" v-model="formInline.state" placeholder="请选择">
                <el-option
                  v-for="item in [{
                    value: '1',
                    label: '上架'
                  },{
                    value: '0',
                    label: '下架'
                  },]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="primary" @click="onSubmit">搜索</el-button>
              <el-button size="small" @click="resetSubmit">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div style="display:flex;align-items:center;">
          <el-button size="small" type="primary" @click="add">新建商品</el-button>
        </div>
      </div>

    <el-table ref="multipleTable" v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row empty-text="暂无数据">
      <el-table-column label="ID" width="150">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="商品名称" width="0">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="缩略图" width="140">
        <template slot-scope="scope">
          <img :src="scope.row.thumbUrl" style="width:100px;height:100px" alt="">
        </template>
      </el-table-column>
      <el-table-column label="商品图" width="140">
        <template slot-scope="scope">
          <img :src="scope.row.imageUrl" style="width:100px;height:100px" alt="">
        </template>
      </el-table-column>
      <el-table-column label="分类" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.typeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品原价" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.orignPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品现价" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.salerPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" width="200">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-tag style="cursor:pointer;" size="small" v-if="scope.row.state == 0" type="danger">下架</el-tag>
          <el-tag style="cursor:pointer;" size="small" v-else type="success">上架</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button @click="changeState(scope.row, 0)" type="text" style="color:#ff0000;" v-if="scope.row.state == 1">下架</el-button>
          <el-button @click="changeState(scope.row, 1)" type="text" v-else>上架</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button @click="edit(scope.row)" type="text">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm
            @onConfirm="del(scope.row)"
            confirm-button-text='确定'
            cancel-button-text='取消'
            icon="el-icon-info"
            icon-color="red"
            title="是否删除本条数据？">
            <el-button  slot="reference" type="text" style="color:#ff0000;">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin:10px 0 0 0;text-align:right;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageObj.pageNum"
        :page-sizes="[10, 30, 50, 100]"
        :page-size="pageObj.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageObj.total">
      </el-pagination>
    </div>

    <el-drawer
      title="商品管理"
      :visible.sync="drawerVisible"
      destroy-on-close
      size="70%"
      direction="rtl">
      <div style="padding:0 20px;overflow-x: hidden;overflow-y: auto;height: calc(100vh - 80px);position: relative">
        <div style="display:flex;align-items:center;margin-bottom: 20px;">
          <div style="text-align:right;width:100px;margin-right:20px;">
            商品分类
          </div>
          <div style="flex: 1;">
            <el-select style="width:100%;" clearable v-model="goodsObj.type" placeholder="请选择商品分类">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div style="display:flex;align-items:center;margin-bottom: 20px;">
          <div style="text-align:right;width:100px;margin-right:20px;">
            商品名称
          </div>
          <div style="flex: 1;">
            <el-input clearable v-model="goodsObj.goodsName" placeholder="请输入商品名称"></el-input>
          </div>
        </div>
        <div style="display:flex;margin-bottom: 20px;">
          <div style="text-align:right;width:100px;margin-right:20px;margin-top: 10px;">
            商品缩略图（290*282）
          </div>
          <div style="flex: 1;">
            <el-upload
              :class="smallFilesList.length!=''?'hiddenUpload':''"
              action="https://service.bairicun.com/file/upload"
              list-type="picture-card"
              :file-list="smallFilesList"
              :on-success="handleSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </div>
        </div>
        <div style="display:flex;margin-bottom: 20px;">
          <div style="text-align:right;width:100px;margin-right:20px;margin-top: 10px;">
            商品主图（290*282）
          </div>
          <div style="flex: 1;">
            <el-upload
              :class="mainFilesList.length!=''?'hiddenUpload':''"
              action="https://service.bairicun.com/file/upload"
              list-type="picture-card"
              :file-list="mainFilesList"
              :on-success="handleMainSuccess"
              :on-preview="handleMainPictureCardPreview"
              :on-remove="handleMainRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogMainVisible">
              <img width="100%" :src="dialogMainUrl" alt="">
            </el-dialog>
          </div>
        </div>
        <div style="display:flex;align-items:center;margin-bottom: 20px;">
          <div style="text-align:right;width:100px;margin-right:20px;">
            商品原价
          </div>
          <div style="flex: 1;">
            <el-input type="number" clearable v-model="goodsObj.price" placeholder="请输入商品原价"></el-input>
          </div>
        </div>
        <div style="display:flex;align-items:center;margin-bottom: 20px;">
          <div style="text-align:right;width:100px;margin-right:20px;">
            商品现价
          </div>
          <div style="flex: 1;">
            <el-input type="number" clearable v-model="goodsObj.nowPrice" placeholder="请输入商品现价"></el-input>
          </div>
        </div>
        <div style="display:flex;align-items:center;margin-bottom: 20px;">
          <div style="text-align:right;width:100px;margin-right:20px;">
            商品库存数量
          </div>
          <div style="flex: 1;">
            <el-input type="number" clearable v-model="goodsObj.quantity" placeholder="请输入商品库存数量"></el-input>
          </div>
        </div>
        <div style="display:flex;align-items:center;margin-bottom: 20px;">
          <div style="text-align:right;width:100px;margin-right:20px;">
            商品排序
          </div>
          <div style="flex: 1;">
            <el-input type="number" clearable v-model="goodsObj.sequencing" placeholder="请输入商品排序"></el-input>
          </div>
        </div>
        <div style="display:flex;margin-bottom: 20px;">
          <div style="text-align:right;width:100px;margin-right:20px;margin-top: 10px;">
            商品详情
          </div>
          <div style="flex: 1;">
            <tinymce v-model="goodsObj.description" :height="300" placeholder="请输入商品详情"/>
          </div>
        </div>
        <div style="display:flex;margin-bottom: 20px;justify-content: flex-end;">
          <el-button @click="drawerVisible = false" plain>取消</el-button>
          <el-button @click="saveSellGoods" type="primary">保存</el-button>
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import {
  getGoodsListApi,
  getClassifyListApi,
  addSellGoodsApi,
  sellGoodsStateChangeApi,
  deleteSellGoodsApi,
  getSellGoodsDetailApi
} from '@/api/goods'
import Tinymce from '@/components/Tinymce'

export default {
  components: {
    Tinymce
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      listLoading: true,
      currentPage: 1,
      formInline: {
        isShow: '',
        classify: '',
        state: '',
        title: ''
      },
      pageObj: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      typeList: [],
      drawerVisible: false,
      goodsObj: {
        id: '',
        goodsName: '',
        price: '',
        nowPrice: '',
        quantity: '',
        sequencing: '',
        description: '',
        type: ''
      },
      uploadSmallUrl: '',
      uploadSmallId: '',
      smallFilesList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      uploadMainUrl: '',
      uploadMainId: '',
      mainFilesList: [],
      dialogMainUrl: '',
      dialogMainVisible: false
    }
  },
  created() {
    this.fetchData()
    this.getTypeList()
  },
  methods: {
    add() {
      this.clearGoodsObj()
      this.drawerVisible = true
    },
    closeGoodsDraw() {
      this.clearGoodsObj()
      this.drawerVisible = false
    },
    clearGoodsObj() {
      this.goodsObj.id = ''
      this.goodsObj.goodsName = ''
      this.uploadSmallId = ''
      this.smallFilesList = []
      this.uploadSmallUrl = ''
      this.uploadMainId = ''
      this.mainFilesList = []
      this.uploadMainUrl = ''
      this.goodsObj.type = ''
      this.goodsObj.price = ''
      this.goodsObj.nowPrice = ''
      this.goodsObj.quantity = ''
      this.goodsObj.sequencing = ''
      this.goodsObj.description = ''
    },
    edit(row) {
      getSellGoodsDetailApi({
        id: row.id
      }).then((res) => {
        this.goodsObj.id = res.data.id
        this.goodsObj.goodsName = res.data.name
        this.uploadSmallId = res.data.thumb
        this.uploadSmallUrl = res.data.thumbUrl
        this.smallFilesList = [
          {
            url: res.data.thumbUrl,
            id: res.data.thumb
          }
        ]
        this.uploadMainId = res.data.image
        this.uploadMainUrl = res.data.imageUrl
        this.mainFilesList = [
          {
            url: res.data.imageUrl,
            id: res.data.image
          }
        ]
        this.goodsObj.type = res.data.type
        this.goodsObj.price = res.data.orignPrice
        this.goodsObj.nowPrice = res.data.salerPrice
        this.goodsObj.quantity = res.data.quantity
        this.goodsObj.sequencing = res.data.sequencing
        this.goodsObj.description = res.data.description
        this.drawerVisible = true
      })
    },
    saveSellGoods() {
      addSellGoodsApi({
        source: 'sell',
        id: this.goodsObj.id,
        name: this.goodsObj.goodsName,
        thumb: this.uploadSmallId,
        image: this.uploadMainId,
        type: this.goodsObj.type,
        cost: 0,
        orignPrice: this.goodsObj.price,
        salerPrice: this.goodsObj.nowPrice,
        quantity: this.goodsObj.quantity,
        sequencing: this.goodsObj.sequencing,
        description: this.goodsObj.description
      }).then((res) => {
        this.$message.success('操作成功！')
        this.drawerVisible = false
        this.fetchData()
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess(e) {
      if(e.code == 200) {
        this.uploadStatus = true
        this.uploadSmallUrl = e.data.url
        this.uploadSmallId = e.data.id
        this.smallFilesList = [
          {
            url: e.data.url,
            id: e.data.id
          }
        ]
      }
    },
    handleRemove(file, fileList) {
      this.uploadSmallId = ''
      this.uploadSmallUrl = ''
      this.smallFilesList = []
    },
    handleMainPictureCardPreview(file) {
      this.dialogMainUrl = file.url
      this.dialogMainVisible = true
    },
    handleMainSuccess(e) {
      if(e.code == 200) {
        this.uploadStatus = true
        this.uploadMainUrl = e.data.url
        this.uploadMainId = e.data.id
        this.uploadMainUrl = [
          {
            url: e.data.url,
            id: e.data.id
          }
        ]
      }
    },
    handleMainRemove(file, fileList) {
      this.uploadMainUrl = ''
      this.uploadMainId = ''
      this.mainFilesList = []
    },
    onSubmit() {
      this.fetchData()
    },
    changeState(row, state) {
      sellGoodsStateChangeApi({
        id: row.id,
        state: state
      }).then((res) => {
        this.fetchData()
      })
    },
    getTypeList() {
      getClassifyListApi({
        pageSize: 100,
        pageNum: 1
      }).then((res) => {
        this.typeList = res.data.result.map((r) => {
          return {
            value: r.id,
            label: r.name
          }
        })
      })
    },
    del(row) {
      deleteSellGoodsApi({
        ids: row.id
      }).then((res) => {
        this.fetchData()
      })
    },
    resetSubmit() {
      this.formInline.isShow = ''
      this.formInline.state = ''
      this.formInline.title = ''
      this.formInline.typeId = ''
      this.pageObj.pageSize = 10
      this.pageObj.pageNum = 1
      this.pageObj.total = 0
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      getGoodsListApi({
        source: 'sell',
        state: this.formInline.state,
        name: this.formInline.title,
        type: this.formInline.classify,
        pageSize: this.pageObj.pageSize,
        pageNum: this.pageObj.pageNum
      }).then(response => {
        this.list = response.data.result
        this.pageObj.total = response.data.total
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageObj.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pageObj.pageNum = val
      this.fetchData()
    }
  }
}
</script>

<style>
.v-modal{
  z-index: 1 !important;
}
.hiddenUpload .el-upload--picture-card{
  display:none !important;
}
</style>

<style lang="scss" scoped>
   .news-list{
     padding: 20px;
     .el-form-item{
       margin-bottom: 0;
     }
   }
</style>
